<?php
namespace app\admin\service;

use app\common\model\ProtectModel;
use app\common\model\StationModel;
use app\common\model\UserModel;


class StationService
{
    private static $model;
    private static $userModel;
    private static $protectModel;

    public function __construct(StationModel $stationModel, UserModel $userModel, ProtectModel $protectModel)
    {
        self::$model = $stationModel;
        self::$userModel = $userModel;
        self::$protectModel = $protectModel;
    }

    /**
     * 显示变电站信息列表
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 10:09 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit'])) {
            return app_fail(9997);
        }

        $where = [];
        if (!empty($params['station_name'])) {
            $where[] = ['station_name', 'like', '%'. $params['station_name'] .'%'];
        }

        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        $result = self::$model->where($where)->page($params['page'], $params['limit'])
            ->select();
        // 把 user_id 转换为 nickname
        $userArr = $result->column('user_id');
        $user = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');

        $result->each(function ($item) use ($user) {
            $item->editor = 1;
            $item->nickname = $user[$item->user_id];
            $item->create_time = date('Y-m-d', $item->create_time);
            return $item;
        });

        //检测是否为超级管理员
        $row = self::$userModel->where('id', '=', $params['guid'])->find();
        if ($row['type'] > 1) {
            foreach ($result as $key => $value) {
                $value['editor'] = 0;
                if ($value['user_id'] == $params['guid']) {
                    $value['editor'] = 1;
                }
            }
        }

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * 根据变电站查找对应的保护
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 10:32 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function protect($params)
    {
        if (empty($params) || !isset($params['station_id'])) {
            return app_fail(9997);
        }

        $result = self::$protectModel->where('station_id', '=', $params['station_id'])->select();
        $userArr    = $result->column('user_id');
        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');

        $result->each(function ($item) use ($user) {
            $item->nickname     = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            $item->create_time  = date('Y-m-d', $item->create_time);
            return $item;
        });

        return $result;
    }

    /**
     * 添加变电站信息
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 10:35 PM
     * @param $params
     * @return  mixed
     * @throws \app\common\exception\AppException
     */
    public function create($params)
    {
        if (empty($params)) {
            return app_fail(9997);
        }

        try {
            if (empty($params['id'])) {
                self::$model->allowField(true)->save($params);
            } else {
                self::$model->allowField(true)->save($params, ['id' => $params['id']]);
            }
            return true;
        } catch (\Exception $e) {
            return app_response(9996);
        }
    }

    /**
     * 删除变电站信息
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 10:42 PM
     * @param $params
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete($params)
    {
        if (empty($params) || !isset($params['id'])) {
            return app_fail(9997);
        }

        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        $row = self::$model->where('id', '=', $params['id'])->find();
        if ($user->type != 1 && $row['user_id'] != $params['guid']) {
            return app_fail(1000);
        }

        try {
            self::$model->where('id', '=', $params['id'])->delete();
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 获取所有变电站
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 5:34 PM
     * @param null $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stationAll($params = null)
    {
        $result = self::$model->field(['id', 'station_name'])->select();
        $userData = self::$userModel->field(['id', 'nickname'])->select();
        return ['user' => $userData, 'station' => $result];
    }

}